package com.taoge.p4.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taoge.p4.common.entity.SysUser;
import com.taoge.p4.common.errorCode.SecurityErrorCode;
import com.taoge.p4.common.exception.BusinessException;
import com.taoge.p4.common.mapper.SysUserMapper;
import com.taoge.p4.common.params.LoginParam;
import com.taoge.p4.common.params.SysRegisterParam;
import com.taoge.p4.common.service.SysUserService;
import com.taoge.p4.common.utils.PasswordUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@RequiredArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserMapper sysUserMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void register(SysRegisterParam param) {
        SysUser exist = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, param.getUserName()));
        if (exist != null) {
            throw new BusinessException(SecurityErrorCode.USERNAME_EXISTS_ERROR, param.getUserName(), exist.getCreateTime());
        }

        SysUser sysUser = new SysUser();
        String passwordAndSalt = PasswordUtil.encryptionPassword(param.getPassword());
        String[] split = passwordAndSalt.split("-");
        sysUser.setUsername(param.getUserName());
        sysUser.setPassword(split[0]);
        sysUser.setSalt(split[1]);
        sysUser.setRealName(param.getRealName());
        sysUser.setMobile(param.getMobile());
        sysUser.setLastLoginTime(new Date());
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        sysUserMapper.insert(sysUser);
    }

    @Override
    public SysUser login(LoginParam param) {
        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, param.getUserName()));
        if(sysUser==null){
            throw new BusinessException(SecurityErrorCode.PASSWORD_ERROR);
        }
        // 校验密码是否一致
        String password = PasswordUtil.encryptionPassword(param.getPassword(), sysUser.getSalt());

        // 密码不一致，抛异常
        if (!password.equals(sysUser.getPassword())) {
            throw new BusinessException(SecurityErrorCode.PASSWORD_ERROR);
        }

        return sysUser;
    }
}
